#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022-3-2 13:41
# @Author : huabao.tan
# @File : db.py
# @Software: PyCharm


from pymysql import connect
from tool.sql.config import *



class DB(object):

    def __init__(self):
        self.conn = connect(host=DB_HOST, port=DB_PORT, database=DB_NAME, user=DB_USER, password=DB_PASS)

        # 获取游标
        self.cursor = self.conn.cursor()

    def close(self):
        '''释放数据库资源'''
        self.cursor.close()
        self.conn.close()

    def get_one(self, sql):
        '''使用sql语句查询用户信息'''
        try:
            self.cursor.execute(sql)

            query_result = self.cursor.fetchall()
            if not query_result:
                return None

            fileds = [filed[0] for filed in self.cursor.description]
            return_data = {}
            for filed, value in zip(fileds, query_result):
                return_data[filed] = value

            # return return_data
            return query_result
        except:
            return ''

    def execute_sql(self, sql):
        self.cursor.execute(sql)

    def commit(self):
        self.conn.commit()


if __name__ == '__main__':
    DB()